# -*- coding: utf-8 -*-
"""
角色数据模型
"""

import uuid
from typing import Dict, Any, List, Tuple
from datetime import datetime


class Character:
    """角色模型类"""
    
    def __init__(self, name: str = "", description: str = ""):
        self.id = str(uuid.uuid4())
        self.name = name
        self.description = description
        self.attributes: List[Dict[str, str]] = []  # {"label": "标签", "desc": "描述", "content": "内容"}
        self.position: Tuple[float, float] = (0.0, 0.0)  # 在关系图中的位置
        self.relationships: List[Dict[str, str]] = []  # {"target_id": "目标角色ID", "type": "关系类型", "description": "关系描述"}
        self.created_at = datetime.now()
        self.updated_at = datetime.now()
    
    def add_attribute(self, label: str, desc: str = "", content: str = ""):
        """添加属性"""
        attribute = {
            "label": label,
            "desc": desc,
            "content": content
        }
        self.attributes.append(attribute)
        self.updated_at = datetime.now()
    
    def remove_attribute(self, index: int) -> bool:
        """删除属性"""
        if 0 <= index < len(self.attributes):
            del self.attributes[index]
            self.updated_at = datetime.now()
            return True
        return False
    
    def update_attribute(self, index: int, label: str = None, desc: str = None, content: str = None):
        """更新属性"""
        if 0 <= index < len(self.attributes):
            if label is not None:
                self.attributes[index]["label"] = label
            if desc is not None:
                self.attributes[index]["desc"] = desc
            if content is not None:
                self.attributes[index]["content"] = content
            self.updated_at = datetime.now()
    
    def add_relationship(self, target_id: str, relationship_type: str, description: str = ""):
        """添加关系"""
        relationship = {
            "target_id": target_id,
            "type": relationship_type,
            "description": description
        }
        self.relationships.append(relationship)
        self.updated_at = datetime.now()
    
    def remove_relationship(self, target_id: str, relationship_type: str = None) -> bool:
        """删除关系"""
        for i, rel in enumerate(self.relationships):
            if rel["target_id"] == target_id and (relationship_type is None or rel["type"] == relationship_type):
                del self.relationships[i]
                self.updated_at = datetime.now()
                return True
        return False
    
    def set_position(self, x: float, y: float):
        """设置在关系图中的位置"""
        self.position = (x, y)
        self.updated_at = datetime.now()
    
    def get_attributes_text(self) -> str:
        """获取属性文本描述"""
        if not self.attributes:
            return ""
        
        lines = []
        for attr in self.attributes:
            line = f"{attr['label']}"
            if attr['desc']:
                line += f" - {attr['desc']}"
            if attr['content']:
                line += f": {attr['content']}"
            lines.append(line)
        
        return "\n".join(lines)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            "id": self.id,
            "name": self.name,
            "description": self.description,
            "attributes": self.attributes,
            "position": self.position,
            "relationships": self.relationships,
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat(),
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'Character':
        """从字典创建实例"""
        character = cls(
            name=data.get("name", ""),
            description=data.get("description", "")
        )
        character.id = data.get("id", str(uuid.uuid4()))
        character.attributes = data.get("attributes", [])
        character.position = tuple(data.get("position", (0.0, 0.0)))
        character.relationships = data.get("relationships", [])
        
        # 设置时间
        if "created_at" in data:
            character.created_at = datetime.fromisoformat(data["created_at"])
        if "updated_at" in data:
            character.updated_at = datetime.fromisoformat(data["updated_at"])
        
        return character
    
    def __str__(self) -> str:
        return f"Character({self.name})"
    
    def __repr__(self) -> str:
        return f"Character(id='{self.id}', name='{self.name}')" 